package com.sea.app.module.process.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sea.app.common.excrption.BusinessException;
import com.sea.app.common.Entity.http.Response;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

@RestController
@RequestMapping("/model")
public class ModuleController {

    @Autowired
    private RepositoryService repositoryService;

    @RequestMapping(value = "new")
    public void create(@RequestParam("name") String name, @RequestParam("key") String key,
                       @RequestParam("description") String description, HttpServletRequest request, HttpServletResponse response) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.put("stencilset", stencilSetNode);
            Model modelData = repositoryService.newModel();

            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
            description = StringUtils.defaultString(description);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
            modelData.setMetaInfo(modelObjectNode.toString());
            modelData.setName(name);
            modelData.setKey(StringUtils.defaultString(key));

            repositoryService.saveModel(modelData);
            repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));

            response.sendRedirect(request.getContextPath() + "/modeler.html?modelId=" + modelData.getId());
        } catch (Exception e) {
           e.printStackTrace();
        }
    }

    @RequestMapping(value = "show/{modelId}")
    public void show(@PathVariable("modelId") String modelId,
                               HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.sendRedirect(request.getContextPath()
                + String.format("/modeler.html?modelId=%s",modelId));
    }

    @RequestMapping("deploye/{id}")
    public Object deploye(@PathVariable String id) {
        Model modelData = repositoryService.getModel(id);
        if(modelData == null){
            throw BusinessException.on("model.modelNotFind","未找到模型！");
        }
//         org.activiti.rest.service.api.runtime.task.TaskCollectionResource
        ObjectNode modelNode = null;
        try {
            modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
        } catch (Exception e) {
            e.printStackTrace();
            throw BusinessException.on(e);
        }
        BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
        byte[] bpmnBytes  = new BpmnXMLConverter().convertToXML(model);
        String processName = modelData.getName() + ".bpmn20.xml";
        final Deployment deployment;
        try {
            deployment = repositoryService.createDeployment()
                    .name(modelData.getName())
                    .addString(processName, new String(bpmnBytes,"utf-8")).deploy();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw BusinessException.on(e);
        }
        if (deployment == null || deployment.getId() == null) {
            throw BusinessException.on("model.deployeFail","模型部署失败！");
        }
        return Response.OK.body(deployment);
    }
}